package cn.lngaosu.lwyd.module.integration.service.weixinarticle;

import cn.hutool.core.collection.CollUtil;
import cn.lngaosu.lwyd.framework.common.util.http.HttpUtils;
import cn.lngaosu.lwyd.module.infra.service.config.ConfigService;
import cn.lngaosu.lwyd.module.integration.service.apptoken.AppTokenService;
import cn.lngaosu.lwyd.module.integration.service.weixinuser.WeixinUserServiceImpl;
import cn.lngaosu.lwyd.module.system.dal.dataobject.webinterfacelog.WebinterfaceLogDO;
import cn.lngaosu.lwyd.module.system.dal.mysql.webinterfacelog.WebinterfaceLogMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.lngaosu.lwyd.module.integration.controller.admin.weixinarticle.vo.*;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.weixinarticle.WeixinArticleDO;
import cn.lngaosu.lwyd.framework.common.pojo.PageResult;
import cn.lngaosu.lwyd.framework.common.pojo.PageParam;
import cn.lngaosu.lwyd.framework.common.util.object.BeanUtils;

import cn.lngaosu.lwyd.module.integration.dal.mysql.weixinarticle.WeixinArticleMapper;

import static cn.lngaosu.lwyd.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.convertList;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.diffList;
import static cn.lngaosu.lwyd.module.integration.enums.ErrorCodeConstants.*;

/**
 * 微信文章 Service 实现类
 *
 * @author 张恒
 */
@Service
@Validated
public class WeixinArticleServiceImpl implements WeixinArticleService {
    private static final Logger logger = LoggerFactory.getLogger(WeixinArticleServiceImpl.class);

    @Resource
    private WeixinArticleMapper weixinArticleMapper;
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private ConfigService configService;
    @Resource
    private WebinterfaceLogMapper webinterfaceLogMapper;

    @Override
    public Long createWeixinArticle(WeixinArticleSaveReqVO createReqVO) {
        // 插入
        WeixinArticleDO weixinArticle = BeanUtils.toBean(createReqVO, WeixinArticleDO.class);
        weixinArticleMapper.insert(weixinArticle);
        // 返回
        return weixinArticle.getId();
    }

    @Override
    public void updateWeixinArticle(WeixinArticleSaveReqVO updateReqVO) {
        // 校验存在
        validateWeixinArticleExists(updateReqVO.getId());
        // 更新
        WeixinArticleDO updateObj = BeanUtils.toBean(updateReqVO, WeixinArticleDO.class);
        weixinArticleMapper.updateById(updateObj);
    }

    @Override
    public void deleteWeixinArticle(Long id) {
        // 校验存在
        validateWeixinArticleExists(id);
        // 删除
        weixinArticleMapper.deleteById(id);
    }

    @Override
        public void deleteWeixinArticleListByIds(List<Long> ids) {
        // 校验存在
        validateWeixinArticleExists(ids);
        // 删除
        weixinArticleMapper.deleteByIds(ids);
        }

    private void validateWeixinArticleExists(List<Long> ids) {
        List<WeixinArticleDO> list = weixinArticleMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(WEIXIN_ARTICLE_NOT_EXISTS);
        }
    }

    private void validateWeixinArticleExists(Long id) {
        if (weixinArticleMapper.selectById(id) == null) {
            throw exception(WEIXIN_ARTICLE_NOT_EXISTS);
        }
    }

    @Override
    public WeixinArticleDO getWeixinArticle(Long id) {
        return weixinArticleMapper.selectById(id);
    }

    @Override
    public PageResult<WeixinArticleDO> getWeixinArticlePage(WeixinArticlePageReqVO pageReqVO) {
        return weixinArticleMapper.selectPage(pageReqVO);
    }

    @Override
    public void syncWeixinArticle() {
        // 获取微信token
        String weixinToken = appTokenService.getWeixinToken();
        if (StringUtils.isEmpty(weixinToken)) {
            throw exception(WEIXIN_TOKEN_NOT_EXISTS);
        }

        // 接口配置
        String configValue = configService.getConfigValueByKey("weixinConfig");
        if (StringUtils.isEmpty(configValue)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        JSONObject configJo = JSONObject.parseObject(configValue);
        // 接口开关
        String onOff = configJo.getString("onOff");
        if (!"on".equals(onOff)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        // 获取人员信息列表地址
        String articleUrl = configJo.getString("articleUrl");
        articleUrl = articleUrl + "?access_token=" + weixinToken;

        // 构造请求参数
        JSONObject params = new JSONObject();
        params.put("offset", 0);
        params.put("count", 20);

        // 初始化日志数据（默认成功）
        WebinterfaceLogDO webinterfaceLogDO = new WebinterfaceLogDO();
        webinterfaceLogDO.setInterfaceSystemName("微信公众号");
        webinterfaceLogDO.setInterfaceName("获取文章发布成功列表");
        webinterfaceLogDO.setInterfaceUrl(articleUrl);
        webinterfaceLogDO.setInterfaceRequestMethod("POST");
        webinterfaceLogDO.setInterfaceParam(JSONObject.toJSONString(params));
        webinterfaceLogDO.setInterfaceStatus("成功");
        webinterfaceLogMapper.insert(webinterfaceLogDO);

        try {
            String result = HttpUtils.post(articleUrl, new HashMap<>(), JSONObject.toJSONString(params));

            // 解析接口结果
            JSONObject resultJo = JSONObject.parseObject(result);
            Integer errcode = resultJo.getInteger("errcode");
            if (ObjectUtils.isNotEmpty(errcode)) {
                webinterfaceLogDO.setInterfaceStatus("失败");
                webinterfaceLogDO.setInterfaceErrorInfo(result);
                webinterfaceLogMapper.updateById(webinterfaceLogDO);
                return;
            }
            webinterfaceLogDO.setInterfaceErrorInfo(result);
            webinterfaceLogMapper.updateById(webinterfaceLogDO);

            JSONArray itemJa = resultJo.getJSONArray("item");
            int total_count = resultJo.getIntValue("total_count");
            int size = (total_count + 20 - 1) / 20;

            // 处理数据
            handleData(itemJa);

            for (int i = 1; i < size; i++) {
                params.put("offset", 20 * i);
                result = HttpUtils.post(articleUrl, new HashMap<>(), JSONObject.toJSONString(params));

                // 解析接口结果
                resultJo = JSONObject.parseObject(result);
                errcode = resultJo.getInteger("errcode");
                if (ObjectUtils.isNotEmpty(errcode)) {
                    webinterfaceLogDO.setInterfaceStatus("失败");
                    webinterfaceLogDO.setInterfaceErrorInfo(result);
                    webinterfaceLogMapper.updateById(webinterfaceLogDO);
                    return;
                }

                itemJa = resultJo.getJSONArray("item");

                // 处理数据
                handleData(itemJa);
            }

        } catch (Exception e) {
            webinterfaceLogDO.setInterfaceStatus("失败");
            webinterfaceLogDO.setInterfaceErrorInfo(e.getMessage());
            webinterfaceLogMapper.updateById(webinterfaceLogDO);
            logger.error("微信公众号【获取文章发布成功列表】接口调用失败！", e);
        }


    }

    /**
     * <p>作者: 张恒
     * <p>描述: 处理数据
     * <p>日期: 2025/6/18 13:53
     * @Param itemJa 接口返回数据
     */
    private void handleData(JSONArray itemJa) {
        for (int i = 0; i < itemJa.size(); i++) {
            JSONObject jsonObject = itemJa.getJSONObject(i);
            String article_id = jsonObject.getString("article_id");
            // 如果本地库中有article_id数据，则跳过不处理
            LambdaQueryWrapper<WeixinArticleDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WeixinArticleDO::getArticleId, article_id);
            if (weixinArticleMapper.exists(queryWrapper)) {
                continue;
            }

            JSONObject contentJo = jsonObject.getJSONObject("content");
            Long create_time = contentJo.getLong("create_time");
            Long update_time = contentJo.getLong("update_time");
            JSONArray news_item = contentJo.getJSONArray("news_item");
            for (int j = 0; j < news_item.size(); j++) {
                JSONObject item = news_item.getJSONObject(j);
                WeixinArticleDO weixinArticleDO = BeanUtils.toBean(item, WeixinArticleDO.class);
                weixinArticleDO.setArticleId(article_id);
                weixinArticleDO.setArticleCreateTime(create_time);
                weixinArticleDO.setArticleUpdateTime(update_time);
                weixinArticleMapper.insert(weixinArticleDO);
            }

        }
    }

}